<template>
  <div>
  <el-form label-width="100px" :rules="rules" :model="ruleForm" ref="ruleForm">
    <el-form-item label="头像">
      <img v-if="isEdit" :src="oldImgUrl"
           style="width: 258px;height: 145px;" v-model="ruleForm.imgUrl">
      <el-upload
          action="http://localhost:8080/v1/uploads/article"
          name="file"
          list-type="picture-card"
          :on-success="handleSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item prop="nickName" label="昵称" >
      <el-input  placeholder="请输入昵称"  v-model="ruleForm.nickName"  style="width: 200px"  :rules="{required: true, message: '昵称不能为空', trigger: 'blur'}"></el-input>
    </el-form-item>
    <el-form-item
        label="年龄" prop="age">
      <el-input placeholder="请输入年龄" v-model.number="ruleForm.age" autocomplete="off"  style="width: 200px" ></el-input>
    </el-form-item>
    <el-form-item label="性别" >
      <el-radio-group v-model="ruleForm.gender">
        <el-radio label="男"></el-radio>
        <el-radio label="女"></el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item prop="phone" label="手机号码" >
      <el-input placeholder="请输入手机号" style="width: 200px" v-model="ruleForm.phone"></el-input>
    </el-form-item>
    <el-button style="margin-left: 80px" type="primary" @click="submitForm('ruleForm')">保存信息</el-button>
  </el-form>
  </div>
</template>


<script>
export default {
  name: "ChangeInfoView",
  data: function () {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value < 12) {
            callback(new Error('必须年满12岁'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    return {
      file:{},
      dynamicValidateForm: {
        domains: [{
          value: ''
        }],
      },
      verificationCode: '',
      reponseCode:'',
      isSend:false,
      isCountingDown:false,
      countDownSeconds:60,
      dialogImageUrl: '',
      dialogVisible: false,
      ruleForm:{
        id:localStorage.getItem("id"),
        imgUrl:'',
        nickName: '',
        age:'',
        gender:'',
        phone:'',
      },
      oldImgUrl:'',
      isEdit:false,
      rules: {
        age: [{ validator: checkAge, trigger: 'blur' },
          { required: true, message: '年龄不能为空'},
          { type: 'number', message: '年龄必须为数字值'}],

        email:[
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],

        phone:[{ required: true, message: '请填写手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '手机号码不低于11位数', trigger: 'blur' },
          { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '请输入正确的手机号码格式' }]
      },
    }
  },

  methods: {
    submitForm(formName){
      console.log(this.ruleForm)
      this.$refs[formName].validate((valid)=>{
        if (valid){
          let url="http://localhost:8080/v1/users/update";
          console.log('url =' +url);
          let formDate =this.qs.stringify(this.ruleForm);
          console.log('formDate ='+formDate);
          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
              .post(url,formDate).then((response)=>{
            if (response.data.code==1){
              this.$message.success("修改成功!")
              //发请求退出登录
              this.axios.post("http://localhost:8080/v1/users/logout").then(()=> {
                localStorage.clear();//清空登录成功时保存的数据
                location.href="/login";
              })
            }else {
              this.$message.error(response.data.msg);
            }
          });
        }else {
          console.log('error submit');
          return false;
        }

      })
    },
    handleSuccess(response,file,fileList){//当上传成功时此方法会执行
      // response==file.response 代表服务器响应的ResultVo
      console.log(response.data)
      this.file = response.data;
      this.ruleForm.imgUrl=response.data.url;
    },
    handleRemove(file, fileList) {
      this.url="";
      console.log(file, fileList);
      let formData = this.qs.stringify(this.file)
      //发出删除文件的请求   file.response上传成功时服务器响应的内容ResultVO
      console.log(file.response);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get("http://localhost:8080/v1/uploads/remove" ,formData).then(function () {
        console.log("服务器文件删除完成!");
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleTab(key,keyPath){
      this.menuIndex=key;
    },
  },
  /*mounted() {
    let url ='http://localhost:8080/v1/users/details/'+localStorage.getItem("id");
    console.log('url ='+url);
    this.axios
        .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
        .get(url).then((response)=>{
      let jsonResult=response.data;
      console.log(jsonResult)
      if (jsonResult.code==1){
        this.ruleForm=jsonResult.data;
      }else {
        let title = '您还未登录,请先登录!';
        this.$alert(jsonResult.message, title, {
          confirmButtonText: '确定',
          callback: action => {
            location.href="/login";
          }
        });
      }
    });
  }*/
}
</script>

<style scoped>

</style>